<?php
class install_model extends Model {

    public function install() {
        $config = "<?php \n";
        foreach ( $_POST[ 'db' ] as $k => $v ) {
            define( $k, trim( $v ) );
            $config .= "define('{$k}', '{$v}');\n";
        }

        $APP_KEY = md5( uniqid() );
        $APP_API_KEY = md5( uniqid() );
        $APP_COOKIE = substr( $APP_KEY, 8, 6 );
        $APP_COOKIE_DOMAIN = "." . ltrim( mc_server( "HTTP_HOST" ), "www." );

        $config .= "define('APP_KEY', '" . $APP_KEY . "');\n";
        $config .= "define('APP_API_KEY', '" . $APP_API_KEY . "');\n";
        $config .= "define('APP_COOKIE', '" . $APP_COOKIE . "');\n";
        $config .= "define('APP_COOKIE_DOMAIN', '" . $APP_COOKIE_DOMAIN . "');\n";

        define( 'APP_KEY', $APP_KEY );

        $this->connection();
        $this->run_sql();

        $this->Cache()->update() && $this->show( "更新缓存...\t\t成功" );

        // 写入数据库配置
        file_put_contents( APP_PATH . "/system/config.php", $config ) && $this->show( "创建配置文件...\t\t成功" );
        chmod( APP_PATH . "/system/config.php", 0666 );

        $this->show( "安装完成..." );
    }

    // 导入sql
    private function run_sql() {
        $users = array();
        foreach ( $_POST[ 'user' ] as $k => $v ) {
            $users[ $k ] = trim( $v );
        }
        $dateline = time();
        $ip = mc_server( 'ip' );
        $pass = mc_md5( $users[ 'pass' ] );
        $author = $users[ 'author' ];

        $sql = include APP_PATH . '/system/install/sql.php';
        $sql = trim( str_replace( 'mc_', dbprefix, $sql ) );
        $sqldump = explode( ";\n", $sql );

        foreach ( $sqldump as $query ) {
            if ( substr( $query, 0, 12 ) == 'CREATE TABLE' ) {
                preg_match( "/CREATE TABLE `([a-z0-9_]+?)`/is", $query, $m );
                $name = $m[ 1 ];
                $this->show( "创建表: {$name}     ... 成功" );
            }
            $this->runSql( trim( $query ) );
        }
        return true;
    }

    public function checkDB() {
        foreach ( $_POST[ 'db' ] as $k => $v ) {
            define( $k, trim( $v ) );
        }

        if ( !$conn = @mysql_connect( dbhost, dbuser, dbpass ) ) {
            exit ( "Can not connect to MySQL server : " . mysql_error() );
        }

        if ( !$db = mysql_select_db( dbname, $conn ) ) {
            exit( "Can\'t use " . dbname . " : " . mysql_error() );
        }
        if ( $query = @mysql_query( "SHOW TABLES FROM " . dbname ) ) {
            while ( $row = mysql_fetch_row( $query ) ) {
                if ( preg_match( "/^" . dbprefix . "/", $row[ 0 ] ) ) {
                    @mysql_close( $conn );
                    return 'unique';
                }
            }
        }
        @mysql_close( $conn );
        return 'success';
    }

    private function show( $msg ) {
        echo "<p>{$msg}</p>";
    }
}